# -*- encoding:utf-8 -*-
import time
import datetime
import json

from service.cubeinfo.CubeFetcher import CubeFetcher
from dao.MySqlDAL import MySqlDAL

__author__ = 'shudong.msd'

'''
<span class="stock-name"><div class="name">奥特迅</div><div class="price">SZ002227</div></span><span class="stock-weight weight">1.59%</span>

'''

class CubeStockCrawler(object):

    # 每类组合找前100个当做样本
    __recordCount = 100

    __tablename = 'tb_cube_info'

    __code_list = ['GB2312','GBK','utf-8','ascii','ANSI']

    __sqlUtil = MySqlDAL()


    def set_target(self,target):
        self.__target = target

    # 获取组合的列表
    def get_cubeid_list(self):
        sql_cube = 'SELECT symbol FROM '+self.__tablename+' WHERE date="'+str(datetime.date.today())+'"'
        res_dic = self.__sqlUtil.get_dimensions_rows(sql_cube)
        res_list = list()
        for row in res_dic:
            res_list.append(row['symbol'])

        return res_list

    # 得到股票组合列表信息[{'symbol':symbol,'group':[(id,weight),()]}]
    def get_group_list(self):
        fetcher = CubeFetcher(20)
        fetcher.set_cuTarget(self.__target)
        for item in self.get_cubeid_list():
            fetcher.push(item)

        group_list = list()
        while fetcher.task_left()>0:
            tmp = fetcher.pop()
            if tmp:
                group_list.append(tmp)
            print fetcher.task_left()
            time.sleep(0.1)

        return group_list


    # 写入db
    def writeToDB(self,type=0):
        # 插入info
        cube_list = self.get_group_list()
        keys_info = ['stock_group','update_time']
        source_info = []
        filter_keys_info = ['symbol','date']
        for row in cube_list:
            tmp = list()
            tmp.append(json.dumps(row['group']))
            tmp.append(time.time())

            tmp.append(row['symbol'])
            tmp.append(datetime.date.today())
            source_info.append(tmp)

        return self.__sqlUtil.update_many_batch(keys_info,source_info,self.__tablename,filter_keys_info,50)
